package cn.edu.xust.api.controller;


import cn.edu.xust.Ro.PieData;
import cn.edu.xust.configuration.exception.Default200Exception;
import cn.edu.xust.configuration.exception.ErrorConstant;
import cn.edu.xust.entity.HotelEntity;
import cn.edu.xust.entity.SysRoleEntity;
import cn.edu.xust.entity.SysUserEntity;
import cn.edu.xust.entity.SysUserhotelEntity;
import cn.edu.xust.Ro.FbtWhiteRo;
import cn.edu.xust.Ro.HotelNIDRo;
import cn.edu.xust.service.*;
import cn.edu.xust.util.JWTUtil;
import cn.edu.xust.util.PageUtils;
import cn.edu.xust.util.R;
import cn.edu.xust.util.RedisUtil;
import cn.edu.xust.util.ruoyi.ShiroUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author ufo
 * @email 2575829997@qq.com
 * @date 2022-09-06 17:32:09
 */
@Slf4j
@RestController
@RequestMapping("/api/sysuser")
public class ApiSysUserController {

    public static final String ROOT = "-1";
    public static final String GROUP = "0";
    public static final String GROUP2 = "1";
    public static final String HOTEL = "2";

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private HotelService hotelService;
    @Autowired
    private SysUserhotelService sysUserhotelService;
    @Autowired
    private SysUserroleService sysUserroleService;
    @Autowired
    private SysRoleService sysRoleService;

    /**
     * 获取当前账号可管理的账号
     */
    @PostMapping("/list")
    public R list(@RequestBody JSONObject jsonObject, HttpServletRequest request) throws Default200Exception {

        String token = request.getHeader("authorization");
        String rjwt = token.replace("Bearer ", "");
        String username1 = JWTUtil.getUsername(rjwt);
        String username = jsonObject.getString("username");
        if (!username1.equals(username)) {
            log.info("token用户名{},body用户名{}", username1, username);
            throw new Default200Exception(ErrorConstant.user_vertify_fail);
        }

        //验证当前账户
        SysUserEntity byNameAndPwd = sysUserService.getByName(username);
        if (byNameAndPwd == null) {
            throw new Default200Exception(ErrorConstant.user_not_exist);
        }

        //获取该账号下直系结点
        List<SysUserEntity> sysUserEntities = sysUserService.getdirectListByUser(byNameAndPwd);
        List<Integer> makerids = sysUserEntities.stream().map(SysUserEntity::getUid).collect(Collectors.toList());
        //查询旗下有多少个直接账号
        Map<String, String> map=sysUserService.getgroupbymaikerid(makerids);
        for (SysUserEntity s : sysUserEntities) {
            s.setPassword(map.get(s.getUid()+"")==null?"0":map.get(s.getUid()+""));
        }

        return R.ok().put("data", sysUserEntities);
    }


    /**
     * 获取当前账号可管理的酒店号
     */
    @PostMapping("/hotellist")
    public R hotellist(@RequestBody JSONObject jsonObject, HttpServletRequest request) throws Default200Exception {

        String token = request.getHeader("authorization");
        String rjwt = token.replace("Bearer ", "");
        String username1 = JWTUtil.getUsername(rjwt);
        String username = jsonObject.getString("username");
        if (!username1.equals(username)) {
            log.info("token用户名{},body用户名{}", username1, username);
            throw new Default200Exception(ErrorConstant.user_vertify_fail);

        }
        //获取该账号下可管理的酒店
        SysUserEntity user = sysUserService.getByName(username);
        if (user == null) {
            throw new Default200Exception(ErrorConstant.user_not_exist);
        }
        String utype = user.getUtype();

        List<HotelEntity> list = new ArrayList<>();
        //系统
        if (ROOT.equals(utype)) {
            list = hotelService.list();
        }

        //集团管理
        else if (GROUP.equals(utype)) {
            list = hotelService.getByGroupId(String.valueOf(user.getGid()));
        }

        //集团
        else if (GROUP2.equals(utype)) {
            list = hotelService.getByGroupId(String.valueOf(user.getGid()));

        }

        //酒店
        else if (HOTEL.equals(utype)) {
            List<SysUserhotelEntity> byUid = sysUserhotelService.getByUid(user.getUid());
            List<Integer> collect = byUid.stream().map(SysUserhotelEntity::getHotelid).collect(Collectors.toList());
            list = hotelService.getByHotelidList(collect);
        }


        //转换
        ArrayList<HotelNIDRo> ros = new ArrayList<>();
        for (HotelEntity hotelEntity : list) {
            HotelNIDRo ro = new HotelNIDRo();
            ro.setHotelCname(hotelEntity.getHotelCname());
            ro.setHotelId(String.valueOf(hotelEntity.getHotelId()));
            ros.add(ro);
        }
        return R.ok().put("data", ros);
    }


    /**
     * 当前账号 查询某儿子账号的酒店列表
     */
    @PostMapping("/acnthotellist")
    public R acnthotellist(@RequestBody JSONObject jsonObject, HttpServletRequest request) throws Default200Exception {


        String token = request.getHeader("authorization");
        String rjwt = token.replace("Bearer ", "");
        String username1 = JWTUtil.getUsername(rjwt);
        String username = jsonObject.getString("username");
        String targetuid = jsonObject.getString("targetuid");

        if (!username1.equals(username)) {
            log.info("token用户名{},body用户名{}", username1, username);
            throw new Default200Exception(ErrorConstant.user_vertify_fail);
        }


        //获取该账号下可管理的账号
        SysUserEntity user = sysUserService.getByName(username);
        if (user == null) {
            throw new Default200Exception(ErrorConstant.user_not_exist);
        }

        List<SysUserEntity> sysUserEntities = sysUserService.getListByUser(user);

        List<Integer> collect = sysUserEntities.stream().map(SysUserEntity::getUid).collect(Collectors.toList());

        //检查是否有权查询这个酒店
        List<SysUserEntity> collect1 = sysUserEntities.stream().filter(e -> collect.contains(e.getUid())).collect(Collectors.toList());
        if (collect1.size() == 0) {
            log.info("非法访问{}，尝试获取uid为{}的账户信息", username, targetuid);
            throw new Default200Exception(ErrorConstant.act_have_no_prev_search_the_act);
        }

        //获取该账号信息
        SysUserEntity act = sysUserService.getById(targetuid);
        String utype = act.getUtype();
        Integer gid = act.getGid();
        Integer uid = act.getUid();
        List<HotelEntity> list = new ArrayList<>();
        //系统
        if (ROOT.equals(utype)) {
            list = hotelService.list();
        }
        //集团管理
        else if (GROUP.equals(utype)) {
            list = hotelService.getByGroupId(String.valueOf(gid));
        }
        //酒店
        else if (HOTEL.equals(utype)) {
            List<SysUserhotelEntity> byUid = sysUserhotelService.getByUid(uid);
            List<Integer> collect2 = byUid.stream().map(SysUserhotelEntity::getHotelid).collect(Collectors.toList());
            list = hotelService.getByHotelidList(collect2);
        }
        List<Integer> collect2 = list.stream().map(HotelEntity::getHotelId).collect(Collectors.toList());
        return R.ok().put("data", collect2);
    }


    /**
     * 添加账号
     */
    @PostMapping("/adduser")
    @RequiresPermissions(value = {"8"}, logical = Logical.OR)
    public R adduser(@RequestBody JSONObject jsonObject, HttpServletRequest request) throws Default200Exception {


        //检查当前账号
        String token = request.getHeader("authorization");
        String rjwt = token.replace("Bearer ", "");
        String username = JWTUtil.getUsername(rjwt);
        SysUserEntity maker = sysUserService.getByName(username);

        String uname = jsonObject.getString("uname");
        String pwd = jsonObject.getString("pwd");
        String utype = jsonObject.getString("utype");


        //禁止添加系统管理员
        if (ROOT.equals(utype)) {
            log.info("有非法访问{}", request);
            throw new Default200Exception(ErrorConstant.signfail);
        }


        SysUserEntity sysUser = new SysUserEntity();
        sysUser.setUtype(utype);
        sysUser.setNickname(uname);
        sysUser.setGid(maker.getGid());
        sysUser.setCname(uname);
        sysUser.setPassword(pwd);
        sysUser.setSex("0");
        sysUser.setPic(maker.getPic());
        sysUser.setCt(new Date());
        sysUser.setMakerid(maker.getUid());
        sysUser.setMakername(maker.getCname());
        sysUser.setConfig("{\"fbt\":false}");

        boolean save = sysUserService.save(sysUser);
        if (!save) {
            return R.error();
        }

        return R.ok();
    }

    /**
     * 修改账号密码
     */
    @PostMapping("/updatepwd")
    @RequiresPermissions(value = {"10"}, logical = Logical.OR)
    public R updatepwd(@RequestBody JSONObject jsonObject, HttpServletRequest request) throws Default200Exception {

        Integer uid = jsonObject.getInteger("uid");
        String nickname = jsonObject.getString("nickname");
        String pwd = jsonObject.getString("pwd");
        boolean save = sysUserService.updatePwdNickName(uid, pwd,nickname);
        if (!save) {
            return R.error();
        }
        return R.ok();
    }


    /**
     * 为账号分配角色和酒店
     */
    @PostMapping("/allocation")
    @Transactional(rollbackFor = Exception.class)
    @RequiresPermissions(value = {"10"}, logical = Logical.OR)
    public R allocation(@RequestBody JSONObject jsonObject, HttpServletRequest request) throws Default200Exception {


        List<Integer> checked_role = (List<Integer>) jsonObject.get("checked_role");
        List<Integer> checked_hotel = (List<Integer>) jsonObject.get("checked_hotel");
        Integer uid = jsonObject.getInteger("uid");

        //查询账号
        SysUserEntity user = sysUserService.getById(uid);
        if (user == null) {
            throw new Default200Exception(ErrorConstant.user_not_exist);
        }

        //查询该账号有无派生其他角色 无才能重新分配
        List<SysRoleEntity> sysRoleEntities = sysRoleService.getByMakerid(uid);
        if (sysRoleEntities.size() != 0) {
            log.info("当前账号已经创建了其他角色{}", sysRoleEntities);
            throw new Default200Exception(ErrorConstant.act_already_create_roles);

        }

        String utype = user.getUtype();

        if ("1".equals(utype)) {

        } else if ("2".equals(utype)) {
            //修改userhotel
            boolean b = sysUserhotelService.resetByuid(uid, user.getGid(), checked_hotel);
        } else if ("0".equals(utype)) {
            throw new Default200Exception(ErrorConstant.illegal_access);
        }


        //修改userrole
        boolean a = sysUserroleService.resetByuid(uid, checked_role);


        //删除角色的权限缓存
        String key = "roleinfo:" + user.getCname();
        redisUtil.del(key);


        if (a) {
        } else {
            throw new Default200Exception(ErrorConstant.error_update_failed);
        }

        return R.ok();
    }

    /**
     * 删除一个账户
     */
    @PostMapping("/del")
    @Transactional(rollbackFor = Exception.class)
    @RequiresPermissions(value = {"9"}, logical = Logical.OR)
    public R del(@RequestBody JSONObject jsonObject, HttpServletRequest request) throws Default200Exception {

        Integer uid = jsonObject.getInteger("uid");

        //在user表 删除
        boolean a = sysUserService.removeById(uid);
        //在 userrole表 删除
        sysUserroleService.removeByUid(uid);
        //在 userhotel表 删除
        sysUserhotelService.removeByUid(uid);
        if (a) {

        } else {
            throw new Default200Exception(ErrorConstant.error_update_failed);
        }

        return R.ok();
    }



}
